﻿using System;
using System.Collections.Generic;
using System.Net;
using System.Text;
using DataModel;

namespace FormatUtil
{
    public enum ALARM_TYPE
    {
        超速报警 = 1,
        疲劳驾驶报警 = 2,
        紧急报警 = 3,
        进入指定区域报警 = 4,
        离开指定区域报警 = 5,
        路段堵塞报警 = 6,
        危险路段报警 = 7,
        越界报警 = 8,
        盗警 = 9,
        劫警 = 10,
        偏离路线报警 = 11,
        车辆移动报警 = 12,
        超时驾驶报警 = 13,
        其他报警 = 255
    }
    public class GwUtil
    {
        public static IdGen IdGen808 = new IdGen();

        public static IdGen IdGenTrain = new IdGen();

        #region 报警信息获取
        public static Alarm GetAlarm(string s)
        {
            Alarm alarm = new Alarm();
            string bin = HexToBin(s, 32);
            alarm.SOS = Convert.ToInt32(bin[31].ToString());
            alarm.OverSpeed = Convert.ToInt32(bin[30].ToString());
            alarm.FatigueDriving = Convert.ToInt32(bin[29].ToString());
            alarm.EarlyWarning = Convert.ToInt32(bin[28].ToString());
            alarm.GNSSError = Convert.ToInt32(bin[27].ToString());
            alarm.GNSSOff = Convert.ToInt32(bin[26].ToString());
            alarm.GNSSShort = Convert.ToInt32(bin[25].ToString());
            alarm.Undervoltage = Convert.ToInt32(bin[24].ToString());
            alarm.PowerOff = Convert.ToInt32(bin[23].ToString());
            alarm.LCDError = Convert.ToInt32(bin[22].ToString());
            alarm.WorkON = Convert.ToInt32(bin[21].ToString());
            alarm.WorkOff = Convert.ToInt32(bin[20].ToString());
            alarm.DirverOverTime = Convert.ToInt32(bin[13].ToString());
            alarm.StopOverTime = Convert.ToInt32(bin[12].ToString());
            alarm.AreaInOut = Convert.ToInt32(bin[11].ToString());
            alarm.RoadInOut = Convert.ToInt32(bin[10].ToString());
            alarm.RoadOverTime = Convert.ToInt32(bin[9].ToString());
            alarm.RoadOffSet = Convert.ToInt32(bin[8].ToString());
            alarm.VSSError = Convert.ToInt32(bin[7].ToString());
            alarm.OilError = Convert.ToInt32(bin[6].ToString());
            alarm.Stolen = Convert.ToInt32(bin[5].ToString());
            alarm.IllegalOn = Convert.ToInt32(bin[4].ToString());
            alarm.IllegalMove = Convert.ToInt32(bin[3].ToString());
            alarm.Collide = Convert.ToInt32(bin[2].ToString());
            alarm.SDError = Convert.ToInt32(bin[1].ToString());
            return alarm;
        }
        #endregion

        #region 状态信息获取
        public static Status GetStatus(string s)
        {
            Status status = new Status();
            string bin = HexToBin(s, 32);
            status.Acc = Convert.ToInt32(bin[31].ToString());
            status.Location = Convert.ToInt32(bin[30].ToString());
            status.N_S = Convert.ToInt32(bin[29].ToString());
            status.E_W = Convert.ToInt32(bin[28].ToString());
            status.YunYingStatus = Convert.ToInt32(bin[27].ToString());
            status.GPSEncrypt = Convert.ToInt32(bin[26].ToString());
            status.LoadStatus = Convert.ToInt32(bin[23]+bin[22]);
            status.OilStatus = Convert.ToInt32(bin[21].ToString());
            status.ElectricStatus = Convert.ToInt32(bin[20].ToString());
            status.LockDoor = Convert.ToInt32(bin[19].ToString());
            status.FrontDoor = Convert.ToInt32(bin[18].ToString());
            status.BackDoor = Convert.ToInt32(bin[17].ToString());
            status.Engine = Convert.ToInt32(bin[16].ToString());
            status.KongTiao = Convert.ToInt32(bin[15].ToString());
            status.ShaChe = Convert.ToInt32(bin[14].ToString());
            status.ZuoZhuanXiang = Convert.ToInt32(bin[13].ToString());
            status.YouZhuanXiang = Convert.ToInt32(bin[12].ToString());
            status.YuanGuang = Convert.ToInt32(bin[11].ToString());
            status.JinGuang = Convert.ToInt32(bin[10].ToString());
            status.ZhenDong = Convert.ToInt32(bin[9].ToString());
            status.LaBa = Convert.ToInt32(bin[8].ToString());
            //status.Gao1 = Convert.ToInt32(bin[7].ToString());
            status.Charge = Convert.ToInt32(bin[2].ToString());
            status.WorkON = Convert.ToInt32(bin[1].ToString());
            status.WorkOff = Convert.ToInt32(bin[0].ToString());

            //status.lockStatus = Convert.ToInt32(Reverse(bin.Substring(0,4)));
            //if (status.lockStatus==8)//本地报警状态
            //{
            //    status.lockAlarm = Convert.ToInt32(Reverse(bin.Substring(4, 4)));
            //}

            //status.DiChu1 = Convert.ToInt32(bin[3].ToString());
            //status.SheFang = Convert.ToInt32(bin[2].ToString());
            return status;
        }
        static string Reverse(string original)
        {
            char[] arr = original.ToCharArray();
            Array.Reverse(arr);
            return new string(arr);
        }
        public static string analyzeAlarm(int flag)
        {
            StringBuilder reStr = new StringBuilder();

            byte[] aByte = System.BitConverter.GetBytes(flag);
            Array.Reverse(aByte);

            byte[] cByte = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
            string[] str = { "紧急报警", "超速报警", "", "", "", "", "", "电池欠压", "", "", "上班打卡报警", "下班打卡报警", "", "", "", "", "", "", "",
                        "", "", "", "", "", "", "", "", "", "", "", "", "" };
            for (int i = 3; i > -1; i--)
            {
                for (int j = 0; j < 8; j++)
                {
                    int a = aByte[i] & cByte[j];
                    if (a != 0)
                    {
                        reStr.Append(str[(3 - i) * 8 + j] + ",");
                    }
                    else
                    {
                        reStr.Append("");
                    }
                }
            }
            if (reStr.Length > 0)
            {
                return reStr.ToString().Substring(0, reStr.Length - 1);
            }
            else
            {
                return reStr.ToString();
            }

        }
        public static string analyzeAlarmWs(int flag)
        {
            StringBuilder reStr = new StringBuilder();

            byte[] aByte = System.BitConverter.GetBytes(flag);
            Array.Reverse(aByte);

            byte[] cByte = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
            string[] str = { "b6", "a7", "c8", "d2", "a1", "a3", "a2", "d7", "d6", "d3", "a4", "c9", "", "d2", "d2", "", "", "", "b4",
                        "a6", "b8", "b7", "c4", "c5", "a8", "b3", "a9", "b1", "b2", "c7", "c7", "" };
            for (int i = 3; i > -1; i--)
            {
                for (int j = 0; j < 8; j++)
                {
                    int a = aByte[i] & cByte[j];
                    if (a != 0)
                    {
                        reStr.Append(str[(3 - i) * 8 + j] + ",");
                    }
                    else
                    {
                        reStr.Append("");
                    }
                }
            }
            if (reStr.Length > 0)
            {
                return reStr.ToString().Substring(0, reStr.Length - 1);
            }
            else
            {
                return reStr.ToString();
            }

        }
        public static string analyzeAlarmLock(int flag)
        {
            StringBuilder reStr = new StringBuilder();

            byte[] aByte = System.BitConverter.GetBytes(flag);
            Array.Reverse(aByte);

            byte[] cByte = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
            string[] str = { "锁绳剪断报警", "应急开锁报警", "拆除报警", "开盖报警", "振动报警", "倾斜报警", "翻转报警", "高温报警", "低温报警", "", "", "", "", "", "", "", "", "", "",
                        "", "", "", "", "", "", "", "", "", "", "", "", "" };
            for (int i = 3; i > -1; i--)
            {
                for (int j = 0; j < 8; j++)
                {
                    int a = aByte[i] & cByte[j];
                    if (a != 0)
                    {
                        reStr.Append(str[(3 - i) * 8 + j] + ",");
                    }
                    else
                    {
                        reStr.Append("");
                    }
                }
            }
            if (reStr.Length > 0)
            {
                return reStr.ToString().Substring(0, reStr.Length - 1);
            }
            else
            {
                return reStr.ToString();
            }

        }
        public static string analyzeState(int flag)
        {

            StringBuilder reStr = new StringBuilder();

            byte[] aByte = System.BitConverter.GetBytes(flag);
            Array.Reverse(aByte);

            byte[] cByte = { 0x01, 0x02, 0x04, 0x08, 0x10, 0x20, 0x40, 0x80 };
            string[] str0 = { "静止", "未定位", "", "", "", "", "", "", "", "", "车辆油路正常", "车辆电路正常", "", "", "", "", "", "", "",
                        "", "", "", "", "", "", "", "", "", "", "未接充电器", "上班未打卡", "下班未打卡" };

            string[] str1 = { "运动", "定位", "", "", "", "", "", "", "", "", "车辆油路断开", "车辆电路断开", "", "", "", "", "", "", "",
                        "", "", "", "", "", "", "", "", "", "", "有5V充电", "上班已打卡", "下班已打卡" };

            for (int i = 3; i > -1; i--)
            {
                for (int j = 0; j < 8; j++)
                {
                    if (((3 - i) * 8 + j) == 8)
                    {

                        int a = aByte[i] & cByte[j];
                        int b = aByte[i] & cByte[j + 1];
                        if (a == 0 && b == 0)
                        {
                            //reStr.Append("空车" + ",");
                        }
                        else if (a == 0 && b != 0)
                        {
                            //reStr.Append("半载" + ",");
                        }
                        else if (a != 0 && b == 0)
                        {
                            //reStr.Append("保留" + ",");
                        }
                        else if (a != 0 && b != 0)
                        {
                            //reStr.Append("满载" + ",");
                        }


                    }
                    else
                    {
                        int a = aByte[i] & cByte[j];
                        if (a == 0)
                        {
                            if (str0[(3 - i) * 8 + j]!="")
                            {
                                reStr.Append(str0[(3 - i) * 8 + j] + ",");
                            }
                           
                        }
                        else
                        {
                            if (str1[(3 - i) * 8 + j] != "")
                            {
                                reStr.Append(str1[(3 - i) * 8 + j] + ",");
                            }
                        }
                    }
                }
            }
            if (reStr.Length > 0)
            {
                return reStr.ToString().Substring(0, reStr.Length - 1);
            }
            else
            {
                return reStr.ToString();
            }

        }
        public static VideoAlarmFlag GetVideoAlarm(string s)
        {
            VideoAlarmFlag status = new VideoAlarmFlag();
            string bin = HexToBin(s, 32);
            status.lossVideoSignal = Convert.ToInt32(bin[31].ToString());
            status.occlusionVideoSignal = Convert.ToInt32(bin[30].ToString());
            status.storageFault = Convert.ToInt32(bin[29].ToString());
            status.otherVideoDeviceFault = Convert.ToInt32(bin[28].ToString());
            status.busOverManAlarm = Convert.ToInt32(bin[27].ToString());
            status.abnormalDrivingBehaviorAlarm = Convert.ToInt32(bin[26].ToString());
            status.alarmVideoFull = Convert.ToInt32(bin[25].ToString());
            return status;
        }

        public static AbnormalDrivingBehaviorAlarm GetAbnormalDrivingBehaviorAlarm(string s)
        {
            AbnormalDrivingBehaviorAlarm status = new AbnormalDrivingBehaviorAlarm();
            string bin = HexToBin(s, 32);
            status.fatigue = Convert.ToInt32(bin[31].ToString());
            status.call = Convert.ToInt32(bin[30].ToString());
            status.smoking = Convert.ToInt32(bin[29].ToString());
          
            return status;
        }
        #endregion        

        #region 十六进制转整形
        public static int HexToInt(string Str)
        {
            int i, j, k;
            j = 0;
            i = 0;
            for (k = 1; k <= Str.Length; k++)
            {
                switch (Str[k - 1])
                {
                    case '0':
                    case '1':
                    case '2':
                    case '3':
                    case '4':
                    case '5':
                    case '6':
                    case '7':
                    case '8':
                    case '9':
                        i = Convert.ToInt32(Str[k - 1].ToString());
                        // i = int.Parse(Str[k - 1]);
                        break;
                    case 'A':
                        i = 10;
                        break;
                    case 'B':
                        i = 11;
                        break;
                    case 'C':
                        i = 12;
                        break;
                    case 'D':
                        i = 13;
                        break;
                    case 'E':
                        i = 14;
                        break;
                    case 'F':
                        i = 15;
                        break;
                    case 'a':
                        i = 10;
                        break;
                    case 'b':
                        i = 11;
                        break;
                    case 'c':
                        i = 12;
                        break;
                    case 'd':
                        i = 13;
                        break;
                    case 'e':
                        i = 14;
                        break;
                    case 'f':
                        i = 15;
                        break;

                }
                j = j * 16 + i;
            }
            return j;
        }
        #endregion

        #region 十进制转十六进制
        public static string IntToHex(int n, int len)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Convert.ToString(n, 16).ToUpper());
            while (sb.Length < len)
            {
                sb.Insert(0, "0");
            }
            return sb.ToString();
        }
        #endregion

        #region 十进制转二进制
        public static string IntToBin(int dec, int len = 8)
        {
            string s = Convert.ToString(dec, 2);
            s = s.PadLeft(len, '0');

            return s;
        }
        #endregion

        #region 二进制转十进制
        public static int BinToInt(string s)
        {
            return Convert.ToInt32(s, 2);
        }
        #endregion

        #region 十进制转十进制字符串
        public static string DexToStr(int n, int len)
        {
            string sn = n.ToString();
            sn = sn.PadLeft(len, '0');
            return sn;
        }
        #endregion


        #region 十六进制转二进制
        public static string HexToBin(string hex, int len = 8)
        {
            string s = Convert.ToString(HexToInt(hex), 2);
            while (s.Length < len)
            {
                s = "0" + s;
            }
            return s;
        }
        #endregion

        #region 字节数组转long
        public static long byteArr2long(byte[] buf)
        {
            long result = 0;
            for (int i = 0; i < buf.Length; i++)
            {
                long lNumber = (long)(buf[i] & 0xff) << ((buf.Length - i - 1) * 8);
                result += lNumber;
            }
            return result;
        }
        #endregion


        public static string Bytes2String(byte[] buf, int startindex, int len)
        {
            if (len == 0)
            {
                return string.Empty;
            }
            byte[] bs = new byte[len];
            Buffer.BlockCopy(buf, startindex, bs, 0, len);
            return Encoding.GetEncoding("GBK").GetString(bs);
            //return System.Text.Encoding.Default.GetString(bs);

        }
        public static string BytesGbkStr(byte[] buf, int startindex, int len)
        {
            if (len == 0)
            {
                return string.Empty;
            }
            byte[] bs = new byte[len];
            Buffer.BlockCopy(buf, startindex, bs, 0, len);
            return Encoding.GetEncoding("GBK").GetString(bs);

        }
        public static string IntToHex(UInt32 n, int len)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(Convert.ToString(n, 16).ToUpper());
            while (sb.Length < len)
            {
                sb.Insert(0, "0");
            }
            return sb.ToString();
        }
        public static DateTime UtcToDateTime(long utc)
        {
            DateTime dtStart = new DateTime(1970, 1, 1, 0, 0, 0);
            DateTime ret = dtStart.AddSeconds(utc);

            return ret;
        }
        public static bool IsDate(string strDate)
        {
            try
            {
                DateTime dt = DateTime.ParseExact(strDate, "yyMMddHHmmss", System.Globalization.CultureInfo.CurrentCulture); //不是字符串时会出现异常
                return true;
            }
            catch 
            {
                return false;
            }
        }
        public static int DateTimeToUtc(DateTime dt)
        {
            dt = dt.ToUniversalTime();
            DateTime dtStart = new DateTime(1970, 1, 1, 0, 0, 0);

            return (int)dt.Subtract(dtStart).TotalSeconds;
        }
        public static long DateTimeToUtcM(DateTime dt)
        {
            dt = dt.ToUniversalTime();
            DateTime dtStart = new DateTime(1970, 1, 1, 0, 0, 0);

            return (long)dt.Subtract(dtStart).TotalMilliseconds;
        }
        public static int ToInt32(byte[] value, int startIndex)
        {
            return IPAddress.NetworkToHostOrder(BitConverter.ToInt32(value, startIndex));
        }

        public static string ToBin32(byte[] value, int startIndex, int Len)
        {
            return Convert.ToString(IPAddress.NetworkToHostOrder(BitConverter.ToInt32(value, startIndex)), 2).PadLeft(Len, '0');
        }

        #region 判断校验码是否正确
        /// <summary>
        /// 判断校验码是否正确
        /// </summary>
        /// <param name="buffers"></param>
        /// <returns></returns>
        public static bool ValidateCheckCode(byte[] buffers)
        {
            if (buffers.Length < 2) return false;
            byte x = buffers[1];
            for (int i = 2; i < buffers.Length - 2; i++)
            {
                x = (byte)(x ^ buffers[i]);
            }
            return x.Equals(buffers[buffers.Length - 2]);

        }

        #endregion

        public static Byte[] ProcessTransferredRequest(byte[] buffers)
        {
            //数据转义
            List<byte> bytes = new List<byte>();
            for (var i = 0; i < buffers.Length; i++)
            {
                if (buffers[i] == 0x7D)
                {
                    if (i == buffers.Length - 1)
                    {
                        bytes.Add(buffers[i]);
                    }
                    else
                    {
                        if (buffers[i + 1] == 0x01)
                        {
                            bytes.Add(0x7D);

                            i++;
                        }
                        else if (buffers[i + 1] == 0x02)
                        {
                            bytes.Add(0x7E);
                            i++;
                        }
                        else
                        {
                            bytes.Add(buffers[i]);
                        }
                    }
                }
                else
                {
                    bytes.Add(buffers[i]);
                }
            }
            return bytes.ToArray();
        }


        public static string GetUpgradeTypeDescription(int type)
        {
            if (type == 0x00) return "apk升级指令";
            else if (type == 0x01) return "导航升级指令";
            else if (type == 0x02) return "驱动升级指令";
            else return "未知类型";
        }

        public static byte[] BuildPackage(int msgId, string phoneNum, string body, int msgSerial = 0,int encry=0)
        {
            StringBuilder sb = new StringBuilder();
            sb.Append(IntToHex(msgId, 4));
            if (encry!=0)
            {
                sb.Append(IntToHex(body.Length / 2+ 1024, 4));
            }
            else
            {
                sb.Append(IntToHex(body.Length / 2, 4));
            }

          
            sb.Append(phoneNum.PadLeft(12,'0'));
            if (msgSerial == 0)
                sb.Append(IntToHex(GwUtil.IdGen808.GenId(), 4));
            else
                sb.Append(IntToHex(msgSerial, 4));
            sb.Append(body);
            sb.Append(GetCheckCode(sb.ToString()));

            byte[] bs = BuildTransferredRequest(HexToBytes(sb.ToString()));
            byte[] dataBuffers = new byte[bs.Length + 2];
            dataBuffers[0] = 0x7E;
            Buffer.BlockCopy(bs, 0, dataBuffers, 1, bs.Length);
            dataBuffers[dataBuffers.Length - 1] = 0x7E;
            return dataBuffers;
        }

        public static byte[] addMessageHead(byte[] messageID, int packAllNum, int packNum, byte[] phone, int num, byte[] body) // 消息体添加消息头
        {
            int length;
            byte[] head;
       
            byte[] bsPhone = phone;
            if (packAllNum > 1)
            {
                length = 20;
                head = new byte[length];
                head[0] = 128;
                messageID.CopyTo(head, 1);
                head[3] = (byte)(body.Length / 256 + 32); //32 分包
                head[4] = (byte)(body.Length % 256); //
                bsPhone.CopyTo(head, 5);
                head[13] = (byte)(num / 256);
                head[14] = (byte)(num % 256);
                head[15] = 42;
                head[16] = (byte)(packAllNum / 256);
                head[17] = (byte)(packAllNum % 256);
                head[18] = (byte)(packNum / 256);
                head[19] = (byte)(packNum % 256);
            }
            else
            {
                length = 16;
                head = new byte[length];
                head[0] = 128;
                messageID.CopyTo(head, 1);
                head[3] = (byte)(body.Length / 256);
                head[4] = (byte)(body.Length % 256);
                bsPhone.CopyTo(head, 5);
                head[13] = (byte)(num / 256);
                head[14] = (byte)(num % 256);
                head[15] = 42;
            }

            byte[] sendByte = new byte[length + body.Length + 1];
            Buffer.BlockCopy(head,0,sendByte,0,length);
            //head.CopyTo(sendByte, 0);
            Buffer.BlockCopy(body,0,sendByte,length,body.Length);
            //body.CopyTo(sendByte, length);
            string check = GwUtil.GetCheckCode(GwUtil.BytesToHex(sendByte));
            Buffer.BlockCopy(GwUtil.HexToBytes(check), 0, sendByte, length + body.Length, 1);
            byte[] bs = GwUtil.BuildTransferredRequest(sendByte);
            byte[] dataBuffers = new byte[bs.Length + 2];
            dataBuffers[0] = 0x7E;
            Buffer.BlockCopy(bs, 0, dataBuffers, 1, bs.Length);
            dataBuffers[dataBuffers.Length - 1] = 0x7E;

            return dataBuffers;
        }
        public static Byte[] BuildTransferredRequest(byte[] buffers)
        {
            /*
              标识位：0x7e 消息中出现0x7e转义->0x7d 0x02；
	消息中出现0x7d转义为：0x7d 0x01；
	发送消息转义：消息封装->计算并填充检验码->转义
	接收消息转义：转义还原->验证检验码->解析消息

             */
            //数据转义
            List<byte> bytes = new List<byte>();
            for (var i = 0; i < buffers.Length; i++)
            {
                if (buffers[i] == 0x7E)
                {
                    bytes.Add(0x7D);
                    bytes.Add(0x02);
                }
                else if (buffers[i] == 0x7D)
                {
                    bytes.Add(0x7D);
                    bytes.Add(0x01);
                }
                else
                {
                    bytes.Add(buffers[i]);
                }
            }
            return bytes.ToArray();
        }

        public static int ToInt16(byte[] value, int startIndex)
        {
            //return IPAddress.NetworkToHostOrder(BitConverter.ToInt16(value, startIndex));
            return value[startIndex] * 256 + value[startIndex+1];
        }

        public static string ToBin16(byte[] value, int startIndex, int Len)
        {
            return Convert.ToString(IPAddress.NetworkToHostOrder(BitConverter.ToInt16(value, startIndex)), 2).PadLeft(Len, '0');
        }

        #region 十六进制转字节数组
        public static byte[] HexToBytes(string s)
        {
            byte[] arrByte = new byte[s.Length / 2];
            string tmp = string.Empty;
            try
            {

                int index = 0;

                for (int i = 0; i < s.Length; i += 2)
                {
                    if (i+2<=s.Length)
                    {
                        tmp = s.Substring(i, 2);

                        arrByte[index++] = Convert.ToByte(tmp, 16);
                    }
                          //Convert.ToByte(string,16)把十六进制string转化成byte 
                }
                return arrByte;
            }
            catch (Exception e)
            {
                Console.WriteLine("HexToStr 异常：" + s + e.Message + "  " + e.ToString());
                return arrByte;
            }

        }
        #endregion

        #region 字节数组转十六进制
        public static string BytesToHex(byte[] bs)
        {
            StringBuilder sb = new StringBuilder();
            foreach (byte t in bs)
            {
                var tmp = Convert.ToString(t, 16).PadLeft(2, '0').ToUpper();
                sb.Append(tmp);
            }
            return sb.ToString();
        }
        #endregion

        #region 十六进制转ASSCI
        public static string HexToStr(string s)
        {
            string result = string.Empty;
            string tmp = string.Empty;
            try
            {
                byte[] arrByte = new byte[s.Length / 2];
                int index = 0;

                for (int i = 0; i < s.Length; i += 2)
                {
                    tmp = s.Substring(i, 2);
                    arrByte[index++] = Convert.ToByte(tmp, 16);        //Convert.ToByte(string,16)把十六进制string转化成byte 
                }
                result = Encoding.GetEncoding("GBK").GetString(arrByte);
            }
            catch (Exception e)
            {
                Console.WriteLine("HexToStr 异常：" + tmp + e.Message + "  " + e.ToString());
            }
            return result;

        }
        #endregion

        #region ASSCI转十六进制
        public static string StrToHex(string str)
        {
            string ret = string.Empty;
            string tmp = string.Empty;
            byte[] b = Encoding.GetEncoding("GBK").GetBytes(str);
            for (int i = 0; i < b.Length; i++)
            {
                tmp = Convert.ToString(b[i], 16);
                while (tmp.Length < 2)
                    tmp = "0" + tmp;
                ret = ret + tmp;
            }
            return ret.ToUpper();
        }

        public static string StrToHex(string str, int len)
        {
            string ret = StrToHex(str);
            if (ret.Length > len)
                ret = ret.Substring(0, len);
            else
            {
                while (ret.Length < len)
                {
                    ret += "0";
                }
                    //ret = "0" + ret;

            }
            return ret;
        }
        #endregion

        #region 伪IP转换成设备号
        public static string VipToPhone(string str)
        {
            StringBuilder sb = new StringBuilder();
            int itemp = 0;
            int i1 = HexToInt(str.Substring(0, 2));
            if (i1 >= 0x80)
            {
                itemp = 8;
                i1 = i1 - 0x80;
            }
            sb.Append(string.Format("{0:00}", i1));
            i1 = HexToInt(str.Substring(2, 2));
            if (i1 >= 0x80)
            {
                itemp = itemp + 4;
                i1 = i1 - 0x80;
            }
            sb.Append(string.Format("{0:00}", i1));
            i1 = HexToInt(str.Substring(4, 2));
            if (i1 >= 0x80)
            {
                itemp = itemp + 2;
                i1 = i1 - 0x80;
            }
            sb.Append(string.Format("{0:00}", i1));
            i1 = HexToInt(str.Substring(6, 2));
            if (i1 >= 0x80)
            {
                itemp = itemp + 1;
                i1 = i1 - 0x80;
            }
            if (itemp > 9)
                itemp = itemp + 0x10;
            sb.Insert(0, (130 + itemp).ToString());
            sb.Append(string.Format("{0:00}", i1));
            return sb.ToString();
        }
        #endregion

        #region 设备号转换成伪IP
        public static string PhoneToVip2(string phone)    //伪?àIP换?算?
        {
            string ipaddress = "0.0.0.0";
            try
            {
                byte[] ip_byte = new byte[6];
                if (phone.Length == 11)
                {
                    ip_byte[0] = Convert.ToByte(phone.Substring(0, 1));
                    ip_byte[1] = Convert.ToByte(phone.Substring(1, 2));
                    ip_byte[2] = Convert.ToByte(phone.Substring(3, 2));
                    ip_byte[3] = Convert.ToByte(phone.Substring(5, 2));
                    ip_byte[4] = Convert.ToByte(phone.Substring(7, 2));
                    ip_byte[5] = Convert.ToByte(phone.Substring(9, 2));

                    ip_byte[1] = (byte)((ip_byte[1] - 30) & 0x0f);
                    if ((ip_byte[1] & 0x08) == 0x08)
                    {
                        ip_byte[2] = (byte)(ip_byte[2] + 0x80);
                    }
                    if ((ip_byte[1] & 0x04) == 0x04)
                    {
                        ip_byte[3] = (byte)(ip_byte[3] + 0x80);
                    }
                    if ((ip_byte[1] & 0x02) == 0x02)
                    {
                        ip_byte[4] = (byte)(ip_byte[4] + 0x80);
                    }
                    if ((ip_byte[1] & 0x01) == 0x01)
                    {
                        ip_byte[5] = (byte)(ip_byte[5] + 0x80);
                    }

                    ipaddress = Convert.ToString(ip_byte[2], 16).PadLeft(2, '0') + "" + Convert.ToString(ip_byte[3], 16).PadLeft(2, '0') + "" + Convert.ToString(ip_byte[4], 16).PadLeft(2, '0') + "" + Convert.ToString(ip_byte[5], 16).PadLeft(2, '0');
                    ipaddress = ipaddress.ToUpper();
                }
                else
                {
                    Console.WriteLine("号码长度应为11位", "错误提示");
                }
            }
            catch (Exception ex)
            {
                Console.WriteLine(ex.Message);

            }
            return ipaddress;
        }
        public static string PhoneToVip(string str)
        {
            return PhoneToVip2(str);
        }
        #endregion


        #region 获取校验码
        public static string GetCheckCode(string s)
        {
            int i = 0, r = 0, len, itmp;
            string tmp = string.Empty;
            len = s.Length / 2;
            for (i = 0; i < len; i++)
            {
                tmp = s.Substring((i + 1) * 2 - 2, 2);
                itmp = GwUtil.HexToInt(tmp);
                r = itmp ^ r;
            }
            string ret = Convert.ToString(r, 16).ToUpper();
            ret = ret.PadLeft(2, '0');
            return ret;
        }
        #endregion

     
    }
}

